<template>
    <a-select
            v-on="$listeners"
            v-bind="$attrs"
            :label-in-value="labelInVal"
            show-search
            v-model="currentValue"
            style="width: 100%"
            :filter-option="false"
            :placeholder = "placeholder"
            @popupScroll="(name, e) => (handleScroll(name, e))"
            @search="handleSearch"
            @change="handleChange"
    >
        <a-icon v-if="fetching" style="color:#096dd9;" slot="suffixIcon" type="loading" />
        <a-select-option
                v-for="i in data"
                :key="i.id"
                :value="i.id"
        >{{i.name}}</a-select-option
        >
    </a-select>
</template>
<script>
  import debounce from 'lodash/debounce';
  import { getOrgManageList } from '@/api/system/system'

  export default {
    data() {
      this.lastFetchId = 0;
      this.handleSearch = debounce(this.handleSearch, 800);
      return {
        data: [],
        baseData: [],
        fetching: false,
        noScroll: true,
        pageNumber:1,
        totalPages:1,
        searchVal: '',
      };
    },
    computed:{
      currentValue:{
        get:function() {
          return this.value
        },
        set:function(e) {
          this.$emit('input',e)
          if(e && this.data?.length > 0){
            console.log(e)
            this.$emit('getOption',this.data.find(item=>item.id === e))
          }
        }
      }
    },
    props: {
      value: {
        type: [Object,String,Array,Number],
      },
      orgId:{
        type: [Object,String,Array,Number],
        default: JSON.parse(sessionStorage.getItem('ycloud-user_info')).currentPost.orgId
      },
      culEdu:{
        type: Boolean,
        default: false
      },
      labelInVal:{
        type: Boolean,
        default: false
      },
      placeholder:{
        type: String,
        default: '请输入'
      }
    },
    watch: {
      orgId(oldId, newId){
        console.log(oldId)
        console.log(newId)
        if(oldId != newId){
          this.handleSearch()
        }
      }
    },
    methods: {
      /**
       * 模糊搜索
       */
      handleSearch(value) {
        this.lastFetchId += 1;
        this.data = [];
        this.fetching = true;
        this.searchVal = value;
        this.handleEmployees(value, 1)
      },

      handleChange() {
        Object.assign(this, {
          data: this.baseData,
          fetching: false,
        });
      },
      /**
       * 下拉滚动加载
       */
      handleScroll(e) {
        let that = this;
        const { target } = e
        var total = target.scrollTop + target.offsetHeight
        var scrollHeight = target.scrollHeight
        // this.pageNo是当前页 this.totalPage是总页数
        if (total >= scrollHeight - 1 && total < scrollHeight + 1 && that.pageNumber <= that.totalPages && that.noScroll ) {
          that.pageNumber += 1
          that.handleEmployees()
        }
        if(that.pageNumber > that.totalPages){
          that.noScroll = false;
          that.pageNumber = 1
        }else {
          that.noScroll = true;
        }
      },

      /**
       * 负责人
       * */
      handleEmployees(val, searchPageNumber) {
        this.fetching = true;
        const pageNumber = searchPageNumber ? searchPageNumber : this.pageNumber;
        let params = {
          // pageNumber: pageNumber,
          nameLike: this.searchVal,
          pid: JSON.parse(sessionStorage.getItem('ycloud-user_info')).currentPost.orgId,
          pageNum: pageNumber,
          pageSize: 10000,
          containVirtual: false,
          resultWithLeaderName: true
        }
        getOrgManageList(params).then((res) => {
          if(!val){
            this.data = this.data.concat(res.data.list);
            this.baseData = this.data
          }else {
            const fetchId = this.lastFetchId;
            if (fetchId !== this.lastFetchId) {
              // for fetch callback order
              return;
            }
            this.data = res.data.list
          }
          this.totalPages = res.data.total
          this.fetching = false;
        }).catch(() => {
          this.fetching = false;
        });
      },
    },
    mounted() {
      /**
       * 负责人
       * */
      this.handleEmployees()
    }
  };
</script>